#include "StdAfx.h"
#include "BmpButton.h"

CBmpButton::CBmpButton(void):
mousein(FALSE)
{
}

CBmpButton::~CBmpButton(void)
{
}

BOOL CBmpButton::CreateEx(
						  UINT id,
						  int nX, int nY, int cx, int cy,
						  UINT idNormal, UINT idHot, UINT idSelected,
						  HWND hParent,
						  HINSTANCE hInst
						  )
{
	BOOL ret = CBaseWindow::CreateEx(0, _T("MYBUTTON"), NULL, 
		WS_CHILD,
		nX, nY, cx, cy, hParent, HMENU(0), hInst);
	this->idNormal = idNormal;
	this->idHot = idHot;
	this->idSelected = idSelected;
	this->id = id;
	idCurrent = idNormal;
	LoadString(m_hInst, id, text, 20);

	return ret;
}

LRESULT CBmpButton::WndProcExt(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
	switch(uMsg)
	{
	case WM_SETCURSOR:
		SetCursor(LoadCursor(NULL, IDC_HAND));
		return 1;
	case WM_MOUSEMOVE:
		{
			if(mousein) return 0;
			mousein = TRUE;
			idCurrent = idHot;
			InvalidateRect(m_hWnd, NULL, TRUE);
			TRACKMOUSEEVENT tme;
			tme.cbSize = sizeof(tme);
			tme.hwndTrack = m_hWnd;
			tme.dwFlags = TME_LEAVE;
			TrackMouseEvent(&tme);
		}
		return 0;
	case WM_MOUSELEAVE:
		mousein = FALSE;
		idCurrent = idNormal;
		InvalidateRect(m_hWnd, NULL, TRUE);
		return 0;
	case WM_PAINT:
		{
			PAINTSTRUCT ps;
			BeginPaint(m_hWnd, & ps);
			OnPaint(ps.hdc);
			EndPaint(m_hWnd, & ps);
		}
		return 0;
	case WM_ERASEBKGND:
		return 0;
	default:
		break;
	}
	return ::DefWindowProc(hwnd, uMsg, wParam, lParam);
}

void CBmpButton::OnPaint(HDC dc)
{
	RECT rc;
	GetClientRect(m_hWnd, &rc);
	Graphics g(dc);
	Bitmap bmp(rc.right, rc.bottom);
	Graphics gbmp(&bmp);

	Bitmap btn(m_hInst, MAKEINTRESOURCE(idCurrent));

	gbmp.DrawImage(&btn, 0, 0);

	Brush* brush;
	HFONT hft;
	Bitmap* icon = LoadPng(id);

	if(idCurrent == idSelected)
	{
		hft = CreateFont(12, 0, 0, 0, FW_BOLD, 0, 0, 0, NULL, 0, 0, 0, 0, _T("Tahoma"));
		brush = SolidBrush(Color(0, 0, 0)).Clone();
		gbmp.DrawImage(icon, rc.left+15, rc.top+5, 18, 18);
	}
	else
	{
		hft = CreateFont(12, 0, 0, 0, FW_THIN, 0, 0, 0, NULL, 0, 0, 0, 0, _T("Tahoma"));
		brush = SolidBrush(Color(255, 255, 255)).Clone();
		gbmp.DrawImage(icon, rc.left+20, rc.top+5, 18, 18);
	}
	Font ft(dc, hft);
	StringFormat sf;
	sf.SetLineAlignment(StringAlignmentCenter);
	gbmp.DrawString(text, _tcslen(text), &ft, RectF((REAL)rc.left+37, (REAL)rc.top, (REAL)rc.right, (REAL)rc.bottom), &sf, brush);

	DeleteObject(hft);
	delete(brush);
	delete(icon);
	g.DrawImage(&bmp, 0, 0);
}